<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>树形组件</title>
    <link rel="stylesheet" href="../../res/layui/css/layui.css">
    <script src="../../res/layui/layui.js"></script>
</head>
<body>

<div>
    <div id="tree"></div>
    <button id="btn">输出勾选情况</button>
</div>

<script>
    layui.use(['jquery', 'tree'], function () {
        var $ = layui.jquery;
        var tree = layui.tree;

        // 用于渲染选择树的测试数据
        var testData = [
            {
                "field": "sheng",
                "id": "fj",
                "title": "福建",
                "children": [{"field": "shi", "id": "np", "title": "南平"}, {"field": "shi", "id": "fz", "title": "福州"}, {"field": "shi", "id": "xm", "title": "厦门"}]
            },
            {
                "field": "sheng",
                "id": "zj",
                "title": "浙江",
                "children": [{"field": "shi", "id": "jh", "title": "金华"}, {"field": "shi", "id": "wz", "title": "温州"}, {"field": "shi", "id": "hz", "title": "杭州"}]
            },
            {
                "field": "sheng",
                "id": "gz",
                "title": "广州",
                "children": [{"field": "shi", "id": "dg", "title": "东莞"}, {"field": "shi", "id": "sz", "title": "深圳"}, {"field": "shi", "id": "zh", "title": "珠海"}]
            }
        ];

        // 渲染选择树
        tree.render({
            id: "myTree",
            elem: '#tree',
            showCheckbox: true,
            data: testData,
            oncheck: function (obj) {

                if (obj.checked) {
                    console.log("勾选");
                    if (obj.data.field === "sheng") {
                        // 选中的是父节点
                        console.log("父节点");
                        console.log(obj.data.children);
                    } else {
                        // 选中的是子节点
                        console.log("子节点");
                        console.log(obj.data);
                    }

                } else {
                    console.log("取消");
                    if (obj.data.field === "sheng") {
                        // 取消的是父节点
                        console.log("父节点");
                        console.log(obj.data.children);
                    } else {
                        // 取消的是子节点
                        console.log("子节点");
                        console.log(obj.data);
                    }
                }

            }
        });

        $("#btn").click(function () {
            var checked = tree.getChecked("myTree");
            console.log("\n勾选情况：")
            console.log(checked);
        });

    });
</script>

</body>
</html>
